package com.hnly.djdl.global

import android.util.Log
import com.hnly.djdl.BuildConfig
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL


val scope by lazy { MainScope() }
private var lastEt = ""

// https://blog.csdn.net/qq_43867812/article/details/126883245
fun requestTag(et: String) {
    if (et == lastEt) {
        return
    }
    lastEt = et
    val appVersion = BuildConfig.APP_VERSIONNAME
    val product = BuildConfig.PRODUCT
    if (BuildConfig.DEBUG) {
        Log.i("requestTag", "product=$product, et=$et, lastEt=$lastEt")
    }
    scope.launch(Dispatchers.IO) {
        var connection: HttpURLConnection? = null
        var reader: BufferedReader? = null
        try {
            val uri = "http://alb-rrxcdkp1oi7ko99op6.cn-beijing.alb.aliyuncs.com/gpt/ad/evt/evsave?project=${product}&appVersion=${appVersion}&et=${et}" // &channel=${ChannelUtils.getChannel(null)}
            val url = URL(uri)
            connection = url.openConnection() as HttpURLConnection
            connection.requestMethod = "GET"
            connection.connectTimeout = 8000
            connection.readTimeout = 8000
            val inputStream = connection.inputStream
            val inputStreamReader = InputStreamReader(inputStream)
            reader = BufferedReader(inputStreamReader)
            val text = reader.readText()
            if (BuildConfig.DEBUG) {
                Log.i("requestTag", uri)
                Log.i("requestTag", text)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            if (reader != null) {
                runCatching { reader.close() }
            }
            connection?.disconnect()
        }
    }
}